<template>
  <div>
    <!-- 图片信息-->
    <el-card style="height: 780px" v-loading="pictureLoading">
      <div slot="header" class="search-header">
        <div class="show_title" style="margin-bottom: 5px"> 图片列表：</div>
        <div class="button-group" style="margin-left: auto">
          <el-button type="primary" size="mini" @click="downloadFiles" v-if="downloadFlag">下载</el-button>
          <el-button type="primary" size="mini" @click="downloadChange" v-if="pictureList.length > 0">
            {{ downloadFlag ? '取消' : '批量下载' }}
          </el-button>
        </div>
      </div>
      <ul class="engs-container">
        <li v-for="(picture, index) in pictureList" :key="picture.id">
              <span class="eng-row" @click="selectPicture(picture)" @dblclick="doubleOpen(picture, index)"
                    :class="{ selected: picture === selectedPicture }">
                <input type="checkbox" v-model="picture.selected" @click.stop="selectPictures(picture)" v-if="downloadFlag"/>
                <i class="folder-icon picture-folder-icon"></i>
                <span class="folder-name">{{ picture.picName }}</span>
              </span>
        </li>
      </ul>
      <div class="pagination-container">
        <!-- 分页信息 -->
<!--        <el-pagination small layout="total" :total="pictureTotal"/>-->
        <el-pagination
          small
          @size-change="handleSizeChangePicture"
          @current-change="handleCurrentChangePicture"
          :current-page.sync="pictureQueryParams.pageNum"
          :page-size.sync="pictureQueryParams.pageSize"
          layout="total, prev, pager, next, jumper"
          :pager-count="5"
          :total="pictureTotal"
        ></el-pagination>
      </div>
    </el-card>

    <!--    MP4预览-->
    <el-dialog :visible.sync="videoDialogVisible" center v-loading="loadingMp4" title="文件详情" :before-close="handleVideoDialogClose">
      <video :src="videoUrl"
             autoplay="autoplay"
             ref="vueRef"
             controls width="100%">
        Your browser does not support the video tag.
      </video>
    </el-dialog>
    <!--    图片预览-->
    <el-image-viewer v-if="imgDialogVisible" :zIndex="Number(99999)" :url-list="canvasList"
                     :on-close="closeImgViewer"/>
  </div>
</template>

<script>
import {downloadMore, downloadPic, getFile, getPic, getpictype, listPicture} from "@/api/system/picture_af";

export default {
  components: {
    'el-image-viewer': () => import('element-ui/packages/image/src/image-viewer')
  },
  props: {
    selectedWenJian: Object,
    pictureList: Array,
    pictureTotal: Number,
  },
  data() {
    return {
      canvasList: [],
      pictureList: [], //图片列表
      pictureTotal: 0, //文件总数
      selectedPicture: null,
      pictureQueryParams: {
        // pageNum: 1,
        // pageSize: 20,
        efid: null,
      },
      picSwitch: false,
      pictureLoading: false,
      openPicIndex: '',
      blobImage: "", //图片url
      videoUrl: "", // 存储视频文件的URL地址
      imgDialogVisible: false, // 控制弹窗的显示与隐藏
      videoDialogVisible: false, // 控制弹窗的显示与隐藏
      loadingMp4: false, //MP4加载动画
      selectedPictures: [], // 存储被选中的文件的数组
      downloadFlag: false, //下载显示勾选框
    };
  },
  watch: {
    selectedWenJian(newValue) {
      this.pictureQueryParams.efid = newValue.id
      this.getPictureList();
    }
  },
  created() {
  },
  methods: {
    //获取图片信息
    getPictureList() {
      this.pictureLoading = true;
      listPicture(this.pictureQueryParams).then((response) => {
        setTimeout(() => {
          this.pictureList = response.rows;
          this.pictureTotal = response.total;
          this.pictureLoading = false;
        }, 300);
      }).catch((error) => {
        this.$message.error("获取图片信息失败:" + error);
        this.pictureLoading = false;
      });
    },
    selectPicture(picture) {
      this.selectedPicture = picture;
    },
    //展开/关闭下载
    downloadChange() {
      this.pictureList.forEach((file) => {
        file.selected = false; // 为每个数据对象添加selected属性，初始值为false
      });
      this.selectedPictures = [];
      this.downloadFlag = !this.downloadFlag;
    },
    //选中多个文件
    selectPictures(picture) {
      // 如果文件已经选中，取消选中并从selectedPictures数组中移除
      const index = this.selectedPictures.findIndex(selectedPicture => selectedPicture.id === picture.id);
      if (picture.selected) {
        picture.selected = false;
        if (index !== -1) {
          this.selectedPictures.splice(index, 1); // 使用splice方法移除指定索引的元素
        }
      } else {
        // 如果文件未选中，选中并添加到selectedPictures数组中
        picture.selected = true;
        this.selectedPictures.push(picture);
      }
    },
    //双击预览文件
    doubleOpen(picture, index) {
      picture.id = picture.id.replace(/\//g, "++");
      console.log(picture.id)
      getpictype(picture.id).then((response) => {
        const pictureType = response.toLowerCase(); // 转换为小写以确保比较不区分大小写
        console.log(pictureType)
        if (pictureType === 'pdf') {
          // this.openPDF(picture);
        } else if (pictureType === 'jpg' || pictureType === 'jpeg' || pictureType === 'tif' || pictureType === 'gif' || pictureType === 'png') {
          this.openPicIndex = index
          this.openPicture(this.openPicIndex)
        } else if (pictureType === 'tiff') {
          // this.openTiff(picture);
        } else if (pictureType === 'mp4') {
          this.openMp4(picture);
        }
      });
    },
    async openPicture(index) {
      this.picSwitch = true;
      this.canvasList = [];
      for (let i = index; i < this.pictureList.length; i++) {
        this.fileForm = this.pictureList[i]; // 将文件信息保存到fileForm中，以便在getPdf函数中使用
        await getPic(this.fileForm)
          .then((response) => {
            const blob = new Blob([response], {type: "image/jpeg"});
            this.blobImage = URL.createObjectURL(blob);
            this.canvasList.push(URL.createObjectURL(blob));
          })
          .catch((error) => {
            console.error("获取图片时出错:", error);
            // 可以添加错误处理逻辑，比如显示一个错误提示框等
          });
        if (this.picSwitch === false) {
          return;
        } else {
          this.imgDialogVisible = true; // 显示弹窗
        }
      }
      if (index !== 0) {
        for (let i = 0; i < index; i++) {
          if (this.picSwitch === false) {
            return;
          }
          this.fileForm = this.pictureList[i]; // 将文件信息保存到fileForm中，以便在getPdf函数中使用
          await getPic(this.fileForm)
            .then((response) => {
              const blob = new Blob([response], {type: "image/jpeg"});
              this.blobImage = URL.createObjectURL(blob);
              this.canvasList.push(URL.createObjectURL(blob));
            })
            .catch((error) => {
              console.error("获取图片时出错:", error);
            });
        }
      }
    },
    closeImgViewer() {
      this.picSwitch = false;
      this.canvasList = [];
      this.imgDialogVisible = false;
    },
    openMp4(file) {
      this.videoDialogVisible = true; // 显示弹窗
      this.loadingMp4 = true;
      getFile(file.id).then((response) => {
        const blob = new Blob([response], {type: "video/mp4"});
        this.videoUrl = URL.createObjectURL(blob);
      }).catch((error) => {
        console.error("获取文件时出错:", error);
      });
      this.loadingMp4 = false;
    },
    handleVideoDialogClose(done){
      this.$refs.vueRef.pause();
      done(); // 调用 done() 完成弹窗的关闭操作
    },
    // 下载单个文件
    downloadOnePicture(picture) {
      downloadPic(picture).then((response) => {
        const blob1 = new Blob([response], {type: "image/tiff"});
        const link = document.createElement("a");
        link.href = URL.createObjectURL(blob1);
        link.download = "file.tif";
        link.click();
      })
    },
    //下载多个文件
    downloadFiles() {
      if (this.selectedPictures.length === 0) {
        this.$message({
          message: '请先选择要下载的文件！',
          type: 'warning'
        });
      } else if (this.selectedPictures.length === 1) {
        this.selectedPictures.forEach(picture => {
          this.downloadOnePicture(picture);
        })
      } else {
        let ids = [];
        this.selectedPictures.forEach(picture => {
          let newId = picture.id.replace(/\//g, "++");
          ids.push(newId)
        })
        console.log(ids)
        downloadMore(ids).then((response) => {
          // 处理接收到的二进制ZIP文件数据
          const blob = new Blob([response], {type: "application/zip"});
          const url = window.URL.createObjectURL(blob);
          // 创建一个下载链接并触发点击以下载ZIP文件
          const a = document.createElement('a');
          a.href = url;
          a.download = 'downloaded.zip';
          a.style.display = 'none';
          document.body.appendChild(a);
          a.click();
          window.URL.revokeObjectURL(url);
          this.selectedPictures = []; // 清除多选信息
        });
      }
    },
    handleSizeChangePicture(pageSize) {
      this.pictureQueryParams.pageSize = pageSize;
      this.getPictureList();
    },
    handleCurrentChangePicture(currentPage) {
      this.pictureQueryParams.pageNum = currentPage;
      this.getPictureList();
    },
  },
};
</script>

<style>
/* 公共样式 */
.search-header {
  display: flex;
  justify-content: space-between; /* 将内容分散对齐，使工程信息靠左，其他元素靠右 */
  align-items: center; /* 垂直居中对齐 */
}

.my_input {
  margin-left: auto;
  width: 38%;
}

.show_title {
  flex-grow: 1; /* 工程目录占据剩余空间，将其靠左 */
}

.flex-container {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
}

.button-group {
  margin-left: 10px;
  display: flex;
  justify-content: center;
}

.engs-container {
  height: 600px;
  overflow-y: auto;
  padding: 10px;
  margin-top: -15px;
  border-radius: 4px;
}

.eng-row {
  flex-basis: 100%;
  margin-bottom: -2px;
  display: flex;
  align-items: center;
  padding: 6px 0;
  cursor: pointer;
  transition: background-color 0.3s;
}

.anjuan-row {
  margin-left: -12px;
  flex-basis: 100%;
  margin-bottom: -2px;
  display: flex;
  align-items: center;
  padding: 6px 0;
  cursor: pointer;
  transition: background-color 0.3s;
}

.eng-row:hover {
  background-color: rgba(204, 232, 255, 0.5);
}

.anjuan-row:hover {
  background-color: rgba(204, 232, 255, 0.5);
}

.pagination-container {
  margin-top: 10px;
}

.folder-icon {
  flex-shrink: 0;
  width: 20px;
  height: 20px;
  margin-right: 5px;
  background-size: cover;
}

.folder-name {
  flex-grow: 1;
  font-size: 14px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.show_title {
  font-weight: bold;
  font-size: 20px;
  color: rgb(26, 115, 198);
}

/* 选中状态的样式 */
.selected {
  background-color: #cce8ff;
}

/* 不同图标的样式 */
.eng-folder-icon {
  background-image: url("~@/assets/icons/folder/eng.png");
}

.anJuan-folder-icon {
  background-image: url("~@/assets/icons/folder/anjuan.png");
}

.file-folder-icon {
  background-image: url("~@/assets/icons/folder/file.png");
}

.picture-folder-icon {
  background-image: url("~@/assets/icons/folder/picture.png");
}
</style>
